// pages/home/subscribe/setting/setting.js
import * as user from '../../../../models/user'
import api from "./../../../../common/api"
import * as transferData from '../../../../models/transferData'
import {
  dialog
} from '../../../../component/userStatusDialog/control'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    _isRefreshFollow: false,
    pageIndex: 0,
    pageSize: 20,
    houseList: [],
    hasMoreList: true,
    cityName: '',
    cityCode: '',
    collapseCurrent: '',
    areaList: [],
    saleTypeCurrent: '0',
    saleTypeOptions: [{
      value: '0',
      label: '租售'
    }, {
      value: '1',
      label: '二手'
    }, {
      value: '2',
      label: '出租'
    }],
    infoTypeCurrent: ['0', '1', '2', '3'],
    infoTypeOptions: [{
      value: '0',
      label: '新上'
    }, {
      value: '1',
      label: '带看'
    }, {
      value: '2',
      label: '调价'
    }, {
      value: '3',
      label: '下架'
    }],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
    })
    this.getSubScribeBizcircle()
    this.getRange()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
    this.refreshOfficialAccount()
    this.refreshMySubscribe()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  getRange() {
    return new Promise((resolve, reject) => {
      user.getSubscribeRange()
        .then(res => {
          const {
            subscribeSaleType,
            subscribeInfoType
          } = res
          if (subscribeSaleType && subscribeSaleType !== '-1' && subscribeInfoType && subscribeInfoType !== '-1') {
            this.setData({
              saleTypeCurrent: subscribeSaleType,
              infoTypeCurrent: subscribeInfoType.split(','),
            })
            resolve()
          } else {
            reject()
          }
        })
        .catch(() => {
          reject()
        })
    })
  },

  onSaleTypeChange(e) {
    this.setData({
      saleTypeCurrent: e.detail
    })
  },

  onInfoTypeChange(e) {
    this.setData({
      infoTypeCurrent: e.detail
    })
  },

  onSaveRange() {
    const {
      saleTypeCurrent,
      infoTypeCurrent,
    } = this.data
    if (infoTypeCurrent.length < 1) {
      wx.showToast({
        icon: 'none',
        title: '情报类型不能为空',
      })
      return
    }
    wx.showLoading({
      title: '保存中...',
    })
    user.saveSubscribeRange({
        subscribeSaleType: saleTypeCurrent,
        subscribeInfoType: infoTypeCurrent.join(),
      })
      .then(() => {
        // transferData.setData('isRefreshCooperationSetting', true)
        wx.hideLoading()
        wx.showToast({
          title: '保存成功',
        })
        this.setData({
          hasRangeSetting: true
        })
      })
      .catch(() => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '保存失败，请稍后再试~',
        })
      })
  },

  onClickSubscribe() {
    this.checkOfficialAccount()
      .then(() => {
        wx.navigateTo({
          url: '/pages/home/subscribe/select/select',
        })
      })
      .catch(() => {
        dialog({
          dialog: 'public1',
          confirm: () => {
            this.data._isRefreshFollow = true
            let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
            wx.navigateTo({
              url: `/pages/webView/webView?webViewUrl=${url}`
            })
          }
        })
      })
  },

  checkOfficialAccount() {
    return new Promise((resolve, reject) => {
      user.getOfficialAccount()
        .then(res => {
          if (res === '1') {
            resolve()
          } else {
            reject()
          }
        })
        .catch(() => {
          wx.showToast({
            icon: 'none',
            title: '网络错误，请稍后再试~',
          })
        })
    })
  },

  refreshOfficialAccount() {
    if (this.data._isRefreshFollow) {
      this.data._isRefreshFollow = false
      user.updateOfficialAccount()
    }
  },

  onCollapsesChange(e) {
    this.resetHouseData()
    this.setData({
      collapseCurrent: e.detail
    })
    if (this.data.collapseCurrent) {
      this.getSubScribeResblock()
    }
  },

  // 已订阅商圈列表
  getSubScribeBizcircle() {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '加载中...',
      })
      api.getSubScribeBizcircle({
        pageSize: 100000,
        pageNum: 1,
      }, (res) => {
        if (res && res.data && res.data.isSuccess && res.data.content && res.data.content.list) {
          const {
            areaList
          } = this.data
          this.setData({
            areaList: res.data.content.list
          })
          if (areaList.length !== res.data.content.list.length) {
            this.setData({
              collapseCurrent: ''
            })
          }
          resolve()
        } else {
          reject()
        }
        wx.hideLoading()
      })
    })
  },

  // 商圈id查询小区列表
  getSubScribeResblock() {
    return new Promise((resolve, reject) => {
      const {
        pageIndex,
        pageSize,
        hasMoreList,
      } = this.data
      const {
        bizcircleId = '',
          areaCode = '',
      } = this.data.areaList[this.data.collapseCurrent] || {}
      if (!bizcircleId && !areaCode) {
        wx.showToast({
          icon: 'none',
          title: '未查询到信息...',
        })
        return resolve()
      }
      if (!hasMoreList) {
        return resolve()
      }
      wx.showLoading({
        title: '加载中...',
      })
      let currentIndex = pageIndex + 1
      api.getSubScribeResblock({
        areaCode,
        bizcircleId: bizcircleId || null,
        pageSize: pageSize,
        pageNum: currentIndex
      }, (res) => {
        if (res && res.data && res.data.isSuccess && res.data.content) {
          let result = res.data.content || {}
          let list = result.list || []
          let maxIndex = result.pages
          if (currentIndex === 1) {
            this.data.houseList = [...list]
          } else {
            this.data.houseList.push(...list)
          }
          this.setData({
            pageIndex: currentIndex,
            hasMoreList: currentIndex >= maxIndex ? false : true,
            houseList: this.data.houseList
          })
          resolve()
        } else {
          reject()
        }
        wx.hideLoading()
      }, () => {
        wx.hideLoading()
        reject()
      })
    })
  },

  resetHouseData() {
    this.setData({
      houseList: [],
      pageIndex: 0,
      hasMoreList: true,
    })
  },

  // 取消订阅
  onCancelSubscribe(e) {
    api.subscribe({
      hdResblockId: e.currentTarget.dataset.id,
      stated: 1
    }, res => {
      if (res && res.data && res.data.isSuccess) {
        this.setData({
          pageIndex: 0,
          hasMoreList: true,
        })
        this.getSubScribeBizcircle()
        this.getSubScribeResblock()
        // wx.pageScrollTo({
        //   scrollTop: 0,
        //   duration: 0
        // })
      } else {
        wx.showToast({
          icon: 'none',
          title: '取消订阅失败,请稍后再试~',
        })
      }
    })
  },

  onLoadMore() {
    this.getSubScribeResblock()
  },

  // 检察订阅列表更新
  refreshMySubscribe() {
    if (transferData.getData('isRefreshMySubscribe')) {
      transferData.resetData('isRefreshMySubscribe')
      this.getSubScribeBizcircle()
    }
    if (transferData.getData('isRefreshSubscribeArea')) {
      transferData.resetData('isRefreshSubscribeArea')
      this.getSubScribeBizcircle()
    }
  },

})